from flask import Flask
from flask_sockets import Sockets
import json, time
import _thread
import random

app = Flask(__name__)
sockets = Sockets(app)

ws_pool = []


#file
def read_t_data(filename):
    data = None
    with open(filename, 'r') as f:
        data = f.read().replace('\'','\"');
        data = json.loads(data)
    return data


def read_d_data(filename):
    data = None
    with open(filename, 'r') as f:
        data = f.read().replace('\t',' ')
        items = data.split(' ')
        data = {}
        for item in items:
            val = item.split(':')
            data[val[0]] = val[1]
    return data


#thread
def update(i):
    while True:
        time.sleep(2)
        date = time.strftime('%m-%d-%y %H:%M:%S',time.localtime(time.time()))
        ch1 = float(random.uniform(40,45))
        ch2 = float(random.uniform(3,4))
        ch5 = float(random.uniform(0.7,1))
        ch6 = float(random.uniform(0.01,0.02))
        data = "{{'date': '{0}', 'CH1': {1:.6f}, 'CH2': {2:.6f}, 'CH5': {3:.6f}, 'CH6': {4:.6f}}}".format(date, ch1, ch2, ch5, ch6)
        f = open('temprature.txt', 'w')
        f.write(data)
        f.close()
        data = "{{'DeviceID':10023716, 'node':1, 'tmp':{0:.6f}, 'hum':{1:.6f}}}".format(random.uniform(22,24), random.uniform(29,30))
        f = open('data4.txt', 'w')
        f.write(data)
        f.close()
        data = "{{'DeviceID':10023716, 'node':1, 'tmp':{0:.6f}, 'hum':{1:.6f}}}".format(random.uniform(22,24), random.uniform(29,30))
        f = open('data3.txt', 'w')
        f.write(data)
        f.close()
        data = "{{'DeviceID':10023716, 'node':1, 'tmp':{0:.6f}, 'hum':{1:.6f}}}".format(random.uniform(22,24), random.uniform(29,30))
        f = open('data2.txt', 'w')
        f.write(data)
        f.close()
        data = "{{'DeviceID':10023716, 'node':1, 'tmp':{0:.6f}, 'hum':{1:.6f}}}".format(random.uniform(22,24), random.uniform(29,30))
        f = open('data1.txt', 'w')
        f.write(data)
        f.close()

try:
    _thread.start_new_thread(update, (1,))
except:
   print ("Error: Can't create backend thread.")


#ws://
@sockets.route('/echo')
def echo_socket(ws):
    ws_pool.append(ws)
    while not ws.closed:
        temprature = read_t_data('temprature.txt')
        ws.send(json.dumps(temprature))
        data = read_t_data('data4.txt')
        ws.send(json.dumps(data))
        data = read_t_data('data3.txt')
        ws.send(json.dumps(data))
        data = read_t_data('data2.txt')
        ws.send(json.dumps(data))
        data = read_t_data('data1.txt')
        ws.send(json.dumps(data))
        time.sleep(1)
    ws_pool.remove(ws)


@app.route("/")
def hello():
    return "Hello World!"


if __name__ == "__main__":

    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler

    server = pywsgi.WSGIServer(('0.0.0.0', 5002), app, handler_class=WebSocketHandler)
    print('Running on http://127.0.0.1:5002/')
    server.serve_forever()
